package com.mlc.mlcitems.tracks;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.*;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;

import static com.mlc.mlcitems.Mlcitems.instance;
import static com.mlc.mlcitems.damage.arrowdamage.damageaoe;

public class arrowtracks {
    public static void moveinline(Entity entity, double speed){
        Bukkit.getScheduler().scheduleSyncRepeatingTask(instance,()->{
            if (entity.isDead() || !entity.isValid()) {
                return;
            };
            Location loc =  entity.getLocation();
            Vector direction = loc.getDirection();
            entity.teleport(loc.add(direction.clone().multiply(speed)));
            if(loc.clone().add(direction.clone().multiply(speed)).getBlock().getType().isSolid()){
                entity.remove();
                return;
            };
        },0L,0L);
    }

    public static void moveinlineaoe(Player player, Entity entity, double speed, double range, double damage, double damrange){

        new BukkitRunnable() {
            @Override
            public void run() {
                if (entity.isDead() || !entity.isValid()) {
                    damageaoe(player,entity,damage,damrange);
                    cancel();

                }
                ;
                Location loc = entity.getLocation();
                Vector direction = loc.getDirection();
                entity.teleport(loc.add(direction.clone().multiply(speed)));
                if (loc.clone().add(direction.clone().multiply(speed)).getBlock().getType().isSolid()) {
                    damageaoe(player,entity,damage,damrange);
                    cancel();
                }

                //命中判断
                for (Entity entity1 : entity.getWorld().getNearbyEntities(
                        loc, range, range, range)) {
                    if (entity1 != entity && entity1 != player && entity1 instanceof LivingEntity livingEntity) {
                        damageaoe(player,entity,damage,damrange);
                        cancel();
                    }
                }
            }
        }.runTaskTimer(instance,0L,1L);
    }

    public static void movethrough(Entity entity, double speed){
        Bukkit.getScheduler().scheduleSyncRepeatingTask(instance,()->{
            if (entity.isDead() || !entity.isValid()) {
                return;
            };
            Location loc =  entity.getLocation();
            Vector direction = loc.getDirection();
            entity.teleport(loc.add(direction.clone().multiply(speed)));
        },0L,0L);
    }

    public static void movethrow(Entity entity, double speed){
        Arrow arrow = entity.getLocation().getWorld().spawnArrow(entity.getLocation(),entity.getVelocity(),3,0);
    }
}
